package com.gq.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONException;
import org.json.JSONTokener;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;


public class Client {
	
	private static final String TAG = Client.class.getSimpleName();
	private boolean parseJson = false;
	
	public interface IClientListener {
		void onDone(boolean ok, Object ret);
	}
	
	public void excuteAndListen(String url, IClientListener listener) {
		excuteAndListen(url, listener, true);
	}
	
	public void excuteAndListen(String url, IClientListener listener, boolean parseJson) {
		DownloadTask task = new DownloadTask();
		task.setListener(listener);
		this.parseJson = parseJson;
		task.execute(url);
	}
	
	private class DownloadTask extends AsyncTask<String, Integer, Object> {
		
		private boolean success = false;
		private IClientListener listener;
		public void setListener(IClientListener listener) {
			this.listener = listener;
		}
		
		@Override
		protected Object doInBackground(String... urls) {
			Object ret = null;
			final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("android");
			HttpGet request = new HttpGet(urls[0]);
			try {
				HttpResponse response = httpClient.execute(request);
				final int statusCode = response.getStatusLine().getStatusCode();
				if (statusCode != HttpStatus.SC_OK) return null;
				final HttpEntity httpEntity = response.getEntity();
				String encoding = response.getFirstHeader("Content-Encoding").getValue();
				InputStream is = httpEntity.getContent();
				if (encoding != null && encoding.equals("gzip")) {
					is = new GZIPInputStream(is, 4096);
				}
				byte[] buff = new byte[4096];
				int byteRead = 0;
				StringBuilder sb = new StringBuilder();
				while((byteRead = (is.read(buff))) != -1) {
					sb.append(new String(buff, 0, byteRead));
				}
				is.close();
				success = true;
				return sb.toString();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				httpClient.close();
			}
			return ret;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			if (parseJson) {
				try {
					result = new JSONTokener(String.valueOf(result)).nextValue();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			listener.onDone(success, result);
		}
	}
}
